package com.mdc.log.handler;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.mdc.log.constant.MdcConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import cn.hutool.core.util.StrUtil;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * traceId植入、删除(防止数据膨胀)
 *
 * @author pcheng reviewcode@163.com
 * @date 21:29 2021/7/31
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(MdcConstant.LOG_TRACE_ID);
        if (StrUtil.isNotBlank(traceId)) {
            MDC.put(MdcConstant.LOG_TRACE_ID, traceId);
            return true;
        }
        MDC.put(MdcConstant.LOG_TRACE_ID, new SnowflakeGenerator().next().toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                            @Nullable ModelAndView modelAndView) {
        MDC.remove(MdcConstant.LOG_TRACE_ID);
    }
}
